<template>
  <view class="page">
    <!-- 导航栏 -->
    <uni-nav-bar
      title="积分明细"
      left-icon="left"
      :border="false"
      color="#333"
      fixed
      @clickLeft="goBack"
    />

    <view class="content">
      <!-- 剩余积分 -->
      <view class="balance-card">
        <view class="balance-label">剩余积分</view>
        <view class="balance-amount">
          <text class="balance-value">{{ remainingPoints }}</text>
          <text class="balance-unit">分</text>
        </view>
      </view>

      <!-- 筛选区域 -->
      <!-- <view class="filter-section"> -->
      <!--   <view class="filter-tabs"> -->
      <!--     <view -->
      <!--       v-for="tab in filterTabs" -->
      <!--       :key="tab.value" -->
      <!--       class="filter-tab" -->
      <!--       :class="{ active: currentFilter === tab.value }" -->
      <!--       @click="switchFilter(tab.value)" -->
      <!--     > -->
      <!--       <text class="tab-text">{{ tab.label }}</text> -->
      <!--     </view> -->
      <!--   </view> -->
      <!-- </view> -->

      <!-- 列表内容 -->
      <view class="list-content">
        <!-- 列表项 -->
        <view v-for="item in pointsList" :key="item.id" class="list-item">
          <view class="item-left">
            <view class="title">{{ item.title }}</view>
            <view class="time">{{ item.createTime }}</view>
          </view>
          <view class="item-right">
            <text
              class="points"
              :class="item.type === 'add' ? 'points-add' : 'points-minus'"
            >
              {{ item.type === "add" ? "+" : "-" }}{{ item.points }}
            </text>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="pointsList.length === 0 && !loading" class="empty-state">
          <image
            src="/static/mine/empty.png"
            class="empty-image"
            mode="aspectFit"
          />
          <text class="empty-text">暂无积分记录~</text>
        </view>

        <!-- 加载更多 -->
        <LoadMore
          v-if="pointsList.length > 0"
          :status="loadStatus"
          @retry="loadMore"
        />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from "vue";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import { useRequest } from "ahooks-vue";
import { encryptApi, getPointsDetail, getRemainingPoints } from "@/api";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";
import dayjs from "dayjs";
import rsa from "@/utils/rsa";

const userStore = useUserStore();
const storeStore = useStoreStore();

// 筛选标签
const filterTabs = ref([
  { label: "全部", value: "all" },
  { label: "收入", value: "add" },
  { label: "支出", value: "minus" },
]);

// 当前筛选
const currentFilter = ref("all");

// 剩余积分
const remainingPoints = ref(0);

// 积分列表
const pointsList = ref([]);

// 加载状态
const hasMore = ref(true);
const page = ref(1);
const limit = ref(10);

// 加载状态文本
const loadStatus = computed(() => {
  if (pointsDetailLoading.value) return "loading";
  if (!hasMore.value) return "nomore";
  return "more";
});

// 获取剩余积分
const { run: getRemainingPointsRun } = useRequest(
  () =>
    encryptApi({
      a_d: rsa.encrypt(
        {
          merchantId: storeStore.storeId,
          uid: userStore.userId,
        },
        true,
      ),
      a_m: "cyBerGreenIntegral_manb",
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取剩余积分成功:", response);
      if (response && response.data !== undefined) {
        remainingPoints.value = response.data || 0;
      }
    },
    onError: (error) => {
      console.error("获取剩余积分失败:", error);
    },
  },
);

// // 获取积分明细
// const {
//   data: pointsDetailData,
//   loading: pointsDetailLoading,
//   run: getPointsDetailRun,
// } = useRequest(
//   () =>
//     getPointsDetail({
//       merchantId: storeStore.storeId,
//       uid: userStore.userId,
//       limit: limit.value,
//       offset: page.value,
//     }),
//   {
//     manual: true,
//     onSuccess: (response) => {
//       console.log("获取积分明细成功:", response);
//       if (response && response.data) {
//         loadPointsData(response.data);
//       }
//     },
//     onError: (error) => {
//       console.error("获取积分明细失败:", error);
//       uni.showToast({
//         title: "获取数据失败",
//         icon: "none",
//       });
//     },
//   },
// );
const {
  data: pointsDetailData,
  loading: pointsDetailLoading,
  run: getPointsDetailRun,
} = useRequest(
  () =>
    encryptApi({
      a_d: rsa.encrypt(
        {
          merchantId: storeStore.storeId,
          uid: userStore.userId,
          limit: limit.value,
          offset: page.value,
        },
        true,
      ),
      a_m: "cyBerGreenIntegral_bna",
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("获取积分明细成功:", response);
      if (response && response.data) {
        loadPointsData(response.data);
      }
    },
    onError: (error) => {
      console.error("获取积分明细失败:", error);
      uni.showToast({
        title: "获取数据失败",
        icon: "none",
      });
    },
  },
);

// 加载积分数据
const loadPointsData = (data) => {
  console.log("积分数据:", data);

  // 接口返回格式：{ total: 6, rows: [...] }
  const rows = data?.rows || [];

  if (Array.isArray(rows) && rows.length > 0) {
    const mappedData = rows.map((item, index) => ({
      id: item.id || `${Date.now()}_${index}`,
      title: item.context || "积分变动",
      createTime: item.time
        ? dayjs(item.time).format("YYYY-MM-DD HH:mm:ss")
        : "",
      points: Math.abs(item.money || 0),
      type: item.status === 1 ? "add" : "minus", // status: 1-收入, 0-支出
    }));

    // 第一页替换，其他页追加
    if (page.value === 1) {
      pointsList.value = mappedData;
    } else {
      pointsList.value = [...pointsList.value, ...mappedData];
    }

    // 判断是否还有更多数据
    hasMore.value = mappedData.length >= limit.value;
  } else {
    // 如果不是数组或没有数据
    if (page.value === 1) {
      pointsList.value = [];
    }
    hasMore.value = false;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 切换筛选
const switchFilter = (value) => {
  currentFilter.value = value;
  refreshData();
};

// 刷新数据
const refreshData = () => {
  page.value = 1;
  pointsList.value = [];
  hasMore.value = true;
  loadData();
};

// 加载数据
const loadData = () => {
  if (pointsDetailLoading.value) return;

  console.log("加载积分数据", {
    filter: currentFilter.value,
    page: page.value,
    limit: limit.value,
  });

  getPointsDetailRun();
};

// 加载更多
const loadMore = () => {
  if (pointsDetailLoading.value || !hasMore.value) return;
  page.value += 1;
  loadData();
};

// 页面显示时刷新数据（包括切换店铺后返回）
onShow(() => {
  console.log("积分明细页面显示");
  getRemainingPointsRun(); // 获取剩余积分
  refreshData();
});

// 页面触底事件
onReachBottom(() => {
  loadMore();
});
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  padding: 20rpx 32rpx;
}

// 剩余积分卡片
.balance-card {
  background: linear-gradient(135deg, #4caf50 0%, #81c784 100%);
  border-radius: 16rpx;
  padding: 40rpx 32rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(76, 175, 80, 0.2);
}

.balance-label {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 16rpx;
}

.balance-amount {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
}

.balance-value {
  font-size: 64rpx;
  color: #fff;
  font-weight: 700;
  line-height: 1;
}

.balance-unit {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

// 筛选区域
.filter-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.filter-tabs {
  display: flex;
  gap: 16rpx;
}

.filter-tab {
  flex: 1;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  background-color: #f5f5f5;
  transition: all 0.3s;

  &:active {
    opacity: 0.8;
  }

  &.active {
    background-color: #fabc02;

    .tab-text {
      color: #fff;
      font-weight: 600;
    }
  }
}

.tab-text {
  font-size: 28rpx;
  color: #333;
}

// 列表内容
.list-content {
  min-height: 400rpx;
}

.list-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;
  align-items: center;
  justify-content: space-between;

  &:active {
    opacity: 0.9;
  }
}

.item-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.title {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.time {
  font-size: 24rpx;
  color: #999;
}

.item-right {
  //margin-left: 32rpx;
}

.points {
  font-size: 36rpx;
  font-weight: 600;

  &.points-add {
    color: #4caf50;
  }

  &.points-minus {
    color: #f44336;
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 32rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
